﻿#include"stdafx.h"
#ifdef LK_FUNCTIONAL_ACTION_
namespace LK
{
		/**
		@brief 使用指定的委托和参数数组来创建*/
		ptr<Functional::IActions >::ptr(Functional::PDelegates d, ptr<Collection::IArray<ptr<Object>>> args)
			:Functional::PFunObject<weakptr<Functional::IActions >, VarArgsPack<void, void>, true>(new Functional::IActions())
		{
			if (d==null)Throw<PInvalidArgumentException>(L"指定的委托为空");
			GetPtr()->delegates = d;
			GetPtr()->args = args;
		}
		/**
		@brief 同步执行动作*/
		void ptr<Functional::IActions >::Do() const { Check()->Do(); }
		/**
		@brief 同步执行动作，同Do()*/
		void ptr<Functional::IActions >::operator()()const { Do(); }
		/**
		@brief 启动一个新线程来异步执行动作*/
		index_t ptr<Functional::IActions >::DoSync()const { return Check()->DoSync(); }
		/**
		@brief 获取返回值的引用*/
		ptr<Object>& ptr<Functional::IActions >::GetReturnValRef()const { return Check()->returnVal; }
		/**
		@brief 获取内部委托的引用*/
		Functional::PDelegates& ptr<Functional::IActions >::GetDelegateRef()const { return Check()->delegates; }
		/**
		@brief 获取参数列表数组的引用*/
		ptr<LK::Collection::IArray<ptr<Object>>>& ptr<Functional::IActions >::GetArgumentsRef()const { return Check()->args; }
		ptr<Functional::IActions > ptr<Functional::IActions >::GetNextActionRef()const { return Check()->nextAction; }
		void ptr<Functional::IActions >::Clear()const { Check()->Clear(); }
		/**
		@brief 获取动作当前状态的引用（不一定是准确的，因为获取状态的瞬间可能发生改变）*/
		index_t&  ptr<Functional::IActions >::GetStateRef()const { return Check()->state; }
		/**
		@brief 获取动作已执行的次数的引用（不一定是准确的，，因为获取状态的瞬间可能发生改变）*/
		index_t&  ptr<Functional::IActions >::GetDidCountRef()const { return Check()->didCnt; }
	namespace Functional
	{
		/**
		@brief 默认构造函数*/
		IActions::IActions() :FunObject<weakptr<IActions >, VarArgsPack<void, void>, true>((IActions*)NULL), didCnt(0), state(0)
		{
			FunObject<weakptr<IActions >, VarArgsPack<void, void>, true>::pfun = ((IActions*)this);
		}
		/**
		@brief 复制构造函数*/
		IActions::IActions(IActions const&act) :FunObject<weakptr<IActions >, VarArgsPack<void, void>, true>((IActions*)NULL), didCnt(0), state(0)
		{
			FunObject<weakptr<IActions >, VarArgsPack<void, void>, true>::pfun = this;
			delegates = act.delegates;
			returnVal = act.returnVal;
			args = act.args;
		}
		/**
		@brief 同步执行动作*/
		void IActions::Do() { returnVal = delegates->Invoke(ptr<Object>(), args); }
		/**
		@brief 启动一个新线程来异步执行动作*/
		index_t IActions::DoSync()
		{
			IActions* pAct = this;
			index_t id = APIStartThread(&IActions::ThreadFunction, &pAct);
			while (pAct)Sleep(0);
			return id;
		}
		void IActions::ThreadFunction(void*p)
		{
			ptr<Functional::IActions > act = *(IActions**)p;
			*(IActions**)p = NULL;
			act.Do();
		}
		void IActions::Clear()
		{
			if (args!=null)args.clear();
			args=null;
			delegates=null;
			nextAction=null;
			returnVal=null;
			didCnt = 0;
			state = 0;
		}

	}
}
#endif
